Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.YSEQCGS = function() {

    var myYCGSData = [];
    var YCGSForm = {};
    var YCGSPanel = {};
    var YCGSHash = null;
    var YCGSCount = null;
    var YCGSMaxNum = null;
    var YCGSStore = null;
    var YCGSLoaded = false;
    var selectedSeqRec = {};
    var searchInput = '*';
    var searchOption = 'All';
    var pagingBar = null;
    var spotlightMenu = sptlght.utils.SpotlightUtils.getSpotlightMenu("ycgsspotlightmenuid");

    function initYCGSStore(failedCb, callback) {
        loadYCGSSearchResult(0, null, callback);
    }

    function loadYCGSSearchResult(index, searchResultJSON, callback) {
        myYCGSData = [];
        if (searchResultJSON != null) {
            if (searchResultJSON.results != null) {
                var jsonSearchArray = searchResultJSON.results;
                var ii = 0;
                for (var i = 0; i < jsonSearchArray.length; i++) {
                    if (!jsonSearchArray[i].isFile) {
                        myYCGSData[ii] = translateYCGSResultToJson(jsonSearchArray[i]);
                        ii = ii + 1;
                    }
                }
            }
        }
        YCGSStore = new Ext.ux.data.PagingArrayStore({
            fields: getYCGSPagingColumns(),
            data: myYCGSData,
            sortInfo: {field:'indexNum', direction:'ASC'}
        });
        YCGSStore.load({params:{start:0, limit:10}}, callback());
    }

    function goSearch(index, YCGSSearchInput, YCGSSearchOption) {
        YCGSSearchInput = YCGSSearchInput + "";
        YCGSSearchInput = YCGSSearchInput.replace(/ /g, "%20");
        var freeSearchOp = "FREE_TEXT=" + YCGSSearchInput;
        var matchingAllTerms = "MATCHING_ALL_TERMS=true";
        var matchingSearchHash = "";
        if (YCGSSearchOption == null || YCGSSearchOption == 'All' || YCGSSearchOption == '') {
            matchingAllTerms = "";
            if (YCGSSearchInput == '') {
                YCGSSearchInput = '*';
            }
        } else {
            freeSearchOp = "";
            matchingSearchHash = "&" + YCGSSearchOption + "=" + YCGSSearchInput;
        }
        var searchUrl = getYCGSSearchUrl(freeSearchOp, matchingAllTerms, matchingSearchHash);
        var searchWin = new Ext.Window({
            title: 'Loading CGS',
            width: 400,
            minWidth: 350,
            height: 150,
            modal: true,
            closeAction: 'hide',
            bodyStyle: 'padding:10px;',
            html: "CGS Shell...",
            bbar: new Ext.ux.StatusBar({
                id: 'search-YCGS-statusbar',
                defaultText: 'Ready'
            })
        });
        searchWin.on("show", function () {
            var sb = Ext.getCmp("search-YCGS-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                eventManager.fireStatusMessageEvent({ text: "YCGS Search Results Count:" + searchResultObj.numberOfResults, level: "info" });
                myYCGSData = [];
                loadYCGSSearchResult(index, searchResultObj, function() {
                    Dudley.lims.sequencingmgr.clearPane();
                    searchWin.close();
                    renderYCGSSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadYCGSPanel(doRender) {
        var YCGSsOptionsData = getYCGSSearchOptionsArray();
        var YCGSsOptionsStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : YCGSsOptionsData
        });
        var YCGSCombo = new Ext.form.ComboBox({
            store: YCGSsOptionsStore,
            name: 'YCGSCombo',
            id: 'YCGSComboId',
            fieldLabel: 'On Fields',
            displayField:'value',
            valueField:'key',
            typeAhead: true,
            mode: 'local',
            emptyText:'All',
            triggerAction: 'all',
            forceSelection:true,
            selectOnFocus:true
        });
        var YCGSSearchForm = new Ext.form.FormPanel({
            id: 'YCGSSearchForm',
            method: 'POST',
            autoHeight: true,
            width: 800,
            buttonAlign: 'center',
            title: '',
            keys: [
                {
                    key: [Ext.EventObject.ENTER],
                    fn: function() {
                        Ext.ComponentMgr.get('YCGSSearchButtonId').fireEvent('click');
                    }
                }
            ],

            items: [
                {
                    layout:'column',
                    items:[
                        {
                            columnWidth:.75,
                            border: false,
                            layout: 'form',
                            items: [
                                {
                                    xtype:'textfield',
                                    fieldLabel: 'Search',
                                    id: 'YCGSSearchInputId',
                                    name: 'YCGSSearchInput',
                                    anchor:'95%'
                                }
                            ]
                        },
                        {
                            layout: 'form',
                            border: false,
                            items: [
                                {
                                    xtype: 'button',
                                    fieldAlign: 'center',
                                    text: '&nbsp;&nbsp;Search&nbsp;&nbsp;',
                                    id: 'YCGSSearchButtonId',
                                    listeners:{click:
                                            function() {
                                                var searchInput = Ext.getCmp("YCGSSearchInputId").getValue();
                                                var searchOption = YCGSCombo.getValue();
                                                goSearch(0, searchInput, searchOption);
                                            }}
                                }
                            ]
                        },
                        {
                            columnWidth:1,
                            layout:'form',
                            items: [YCGSCombo]
                        }
                    ]
                }
            ]
        });
        var tbarButtons = [
            {
                id: 'showYCGSSearchResultsId',
                name: 'showYCGSSearchResults',
                disabled: true,
                text: 'Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("wo-form").innerHTML = "";
                            renderYCGSSearchResult();
                        }
                }
            },
            {
                id: 'searchAllYCGSId',
                name: 'searchAllYCGS',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("wo-form").innerHTML = "";
                            goSearch(0, '*', 'All');
                        }
                }
            }
        ];
        YCGSPanel = new Ext.Panel({
            id: "YCGSPanelId",
            autoHeight: true,
            border: true,
            renderTo: "cgs-panel",
            title: "Complete Genome",
            header: false,
            tbar: tbarButtons,
            items: YCGSSearchForm
        });
        YCGSPanel.on("activate", function () {
            Dudley.lims.sequencingmgr.clearPane();
            if (!YCGSLoaded) {
                YCGSLoaded = true;
                goSearch(0, "YCGS*", "All");
            }
            renderYCGSSearchResult();
        });
    }

    function renderSummaryPV(key, coverage, percentage) {
        setCoverageData(Ext.util.JSON.decode(coverage), Ext.util.JSON.decode(percentage));
        window.open("/dudley-lims/cgsplots/cgs_summary_group.html?ycgskey=" + key + "&percentage=" + percentage + "&coverage=" + coverage, "CGS Summary", 'width=500,height=650,scrollbars=yes');
        return;
    }

    function drawClassificationTable(cgskey, chrRange, gene, ctype, annotations, frompopup) {
        var keyWhere = "";
        var rangeWhere = "";
        var geneWhere = "";
        var ctypeWhere = "";
        var annotationsWhere = "";

        if (chrRange.indexOf("chr") != -1) {
            var textArray = chrRange.split(":");
            var range = textArray[1].split("-");
            rangeWhere = "(chrom = '" + textArray[0] + "' and ref_start >= " + range[0] + " and ref_end <= " + range[1] + ")";
        }
        if (cgskey != "") {
            keyWhere = " cgs_key = '" + cgskey + "'";
        } else {
            keyWhere = " cgs_key contains 'YCGS'";
        }
        var andOr = "and";
        if (frompopup) {
            andOr = "or";
        } else if (annotations == "") {
            andOr = "";
        }
        if (annotations != "" && annotations.indexOf("chr") == -1) {
            annotationsWhere = " annotations contains '" + annotations + "'";
        }
        if (gene != "") {
            geneWhere = " " + andOr + " gene = '" + gene + "'";
        }
        if (ctype != "" && ctype != "All" && ctype.indexOf("chr") == -1) {
            ctypeWhere = " " + andOr + " ctype = '" + ctype + "'";
        }
        var customWhere = "";

        if ((annotationsWhere + ctypeWhere + rangeWhere + geneWhere) != "") {
            customWhere = " and ( " + annotationsWhere + ctypeWhere + rangeWhere + geneWhere + ")";
        }
        var querySql = "select cgs_key, strain_key, chrom, strand, ref_start, ref_end, ref_seq, mod_seq, score, gene, ctype, annotations where "
                + keyWhere + customWhere;
        var query = new google.visualization.Query("/google-dsapi-svc/addama/datasources/omics/cgs_changes_classifications/query?tq=" + querySql);
        var omicstable = new google.visualization.Table(document.getElementById('yseq-search-results'));
        query.send(function(response) {
            var omicsjson = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
            if (response.isError()) {
                Ext.Msg.alert("warning", "error at retrieving omics data for cgs query:" + querySql + "<br>" + response.getMessage());
                return;
            }
            var omicsdata = response.getDataTable();
            var rows = omicsdata.getNumberOfRows();
            if (rows > 0) {
                omicstable.draw(omicsdata, {
                    showRowNumber: true,
                    page: "enable",
                    pageSize: 10,
                    size: 'small',
                    height: 450,
                    width: 750,
                    alternatingRowStyle: true,
                    allowHtml: true
                });
                google.visualization.events.addListener(omicstable, 'select', function() {
                    var row = omicstable.getSelection()[0].row;
                    var otype = omicsdata.getValue(row, 1);
                    var strains = omicsdata.getValue(row, 2);                    
                });
                Ext.getCmp("resultsCountId").setValue(""+omicsjson.length);
            } else {
                Ext.getCmp("resultsCountId").setValue('0');
                Ext.Msg.alert("info", "No omics data exists for cgs query:" + querySql);
            }
        });
    }

    function loadClassificationTab(cgskey, text) {
        Dudley.lims.sequencingmgr.clearPane();
        var classificationPanel = Ext.ComponentMgr.get('classificationPanelId');
        if (classificationPanel == null) {
            Dudley.lims.sequencingmgr.getOmicPanel().add({
                title: 'Classifications',
                id: 'classificationPanelId',
                iconCls: 'tabs',
                items: [
                    {
                        layout: 'hbox',
                        width: 800,
                        msgTarget: 'under',
                        items: [
                            new Ext.form.FieldSet({
                                autoHeight: true,
                                border: false,
                                items: [
                                    {
                                        layout: 'hbox',
                                        width: 750,
                                        msgTarget: 'under',
                                        items: [
                                            {
                                                xtype: 'displayfield',
                                                value: '&nbsp;Key&nbsp;'
                                            },
                                            new Ext.form.TextField({
                                                id: "cfkeyid",
                                                width: 70,
                                                value: cgskey,
                                                allowBlank: false,
                                                listeners: {
                                                    render: function(c) {
                                                        Ext.QuickTips.register({
                                                            target: c,
                                                            title: '',
                                                            text: 'CGSKey, leave blank to filter on all cgs records'
                                                        });
                                                    }
                                                }
                                            }),
                                            {
                                                xtype: 'displayfield',
                                                value: '&nbsp;Chr:Start-End&nbsp;'
                                            },
                                            new Ext.form.TextField({
                                                id: "chrrangeid",
                                                width: 120,
                                                allowBlank: false,
                                                listeners: {
                                                    render: function(c) {
                                                        Ext.QuickTips.register({
                                                            target: c,
                                                            title: '',
                                                            text: 'Enter chr:Start-End (ie chrI:100-10000)'
                                                        });
                                                    }
                                                }
                                            }),
                                            {
                                                xtype: 'displayfield',
                                                value: '&nbsp;Gene&nbsp;'
                                            },
                                            new Ext.form.TextField({
                                                id: "genecfid",
                                                width: 70,
                                                allowBlank: true,
                                                listeners: {
                                                    render: function(c) {
                                                        Ext.QuickTips.register({
                                                            target: c,
                                                            title: '',
                                                            text: 'Common gene or systematic name both okay'
                                                        });
                                                    }
                                                }
                                            }),
                                            {
                                                xtype: 'displayfield',
                                                value: '&nbsp;C-Type&nbsp;'
                                            },
                                            {
                                                xtype: 'combo',
                                                id: 'ctypeid',
                                                value: "All",
                                                width: 85,
                                                store: classificationTypeStore,
                                                displayField: 'key',
                                                valueField: 'value',
                                                selectOnFocus: true,
                                                mode: 'local',
                                                typeAhead: true,
                                                editable: false,
                                                triggerAction: 'all',
                                                margins: '0 5 0 0',
                                                listeners: {
                                                    render: function(c) {
                                                        Ext.QuickTips.register({
                                                            target: c,
                                                            title: '',
                                                            text: 'Classification types to filter by'
                                                        });
                                                    }
                                                }
                                            },
                                            {
                                                xtype: 'displayfield',
                                                value: '&nbsp;Annotations&nbsp;'
                                            },
                                            new Ext.form.TextField({
                                                id: "annotationsid",
                                                width: 120,
                                                allowBlank: true,
                                                listeners: {
                                                    render: function(c) {
                                                        Ext.QuickTips.register({
                                                            target: c,
                                                            title: '',
                                                            text: 'Strain physical position'
                                                        });
                                                    }
                                                }
                                            })
                                        ]
                                    },
                                    {
                                        layout: 'hbox',
                                        width: 750,
                                        msgTarget: 'under',
                                        style: {
                                            marginTop: '2px',
                                            marginBottom: '2px'
                                        },
                                        items: [
                                            {
                                                xtype: 'displayfield',
                                                value: '&nbsp;Total Results:&nbsp;'
                                            },
                                            {
                                                xtype: 'displayfield',
                                                id: 'resultsCountId',
                                                value: '&nbsp;&nbsp;'
                                            }
                                        ]
                                    },
                                    {
                                        xtype: 'button',
                                        text: '&nbsp;Search&nbsp;',
                                        id: "searchClassificationsID",
                                        style: {
                                            marginTop: '2px',
                                            marginBottom: '2px'
                                        },
                                        listeners: {
                                            click: function() {
                                                if (Ext.getCmp("genecfid").getValue() != null && Ext.getCmp("genecfid").getValue().length > 1) {
                                                    var genename = Ext.getCmp("genecfid").getValue();
                                                    var geneUri = "/dudley-lims/sequencing/cgs/translategenename?genename=" + genename;
                                                    Ext.Ajax.request({
                                                        url: geneUri,
                                                        method: "GET",
                                                        success: function(response) {
                                                            var respObj = Ext.util.JSON.decode(response.responseText);
                                                            drawClassificationTable(Ext.getCmp("cfkeyid").getValue(), Ext.getCmp("chrrangeid").getValue(), respObj["systematicname"], Ext.getCmp("ctypeid").getValue(), Ext.getCmp("annotationsid").getValue(), false);
                                                        },
                                                        failure: function(response) {
                                                            Ext.Msg.alert("Info", "Gene name was invalid, searching all genes");
                                                            drawClassificationTable(Ext.getCmp("cfkeyid").getValue(), Ext.getCmp("chrrangeid").getValue(), "", Ext.getCmp("ctypeid").getValue(), Ext.getCmp("annotationsid").getValue(), false);
                                                        }
                                                    });
                                                } else {
                                                    drawClassificationTable(Ext.getCmp("cfkeyid").getValue(), Ext.getCmp("chrrangeid").getValue(), "", Ext.getCmp("ctypeid").getValue(), Ext.getCmp("annotationsid").getValue(), false);
                                                }
                                            }
                                        }
                                    }

                                ]
                            })]
                    }
                ],
                keys: [
                    {
                        key: [Ext.EventObject.ENTER],
                        fn: function() {
                            Ext.ComponentMgr.get('searchClassificationsID').fireEvent('click');
                        }
                    }
                ],
                closable:true,
                listeners: {
                    activate: function(p) {
                        Dudley.lims.sequencingmgr.getOmicPanel().activate(classificationPanel);
                        drawClassificationTable(cgskey, text, text, text, text, true);
                    }
                }
            }).show();
        } else {
            classificationPanel.removeAll(true);
        }
    }


    function loadCreateYCGSStrain(YCGSHash, callback) {
        var mytbar = [];
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Submit',
                listeners: {
                    click: function() {
                        var cgsUrl = "/dudley-lims/sequencing/cgs/submit";
                        Ext.Msg.confirm('Message', "Please confirm this CGS data submission, be aware that this submission is asynchronous but in couple of minutes - an email will be send with status of this submission", function(btn) {
                            if (btn == 'yes') {

                                var cgsPanel = Ext.getCmp('YCGSForm');
                                if (cgsPanel.getForm().isValid()) {
                                    if (cgsPanel.baseParams) {
                                        for (i in cgsPanel.baseParams) {
                                            cgsPanel.add(
                                            {  xtype:"hidden",
                                                name:i,
                                                value:cgsPanel.baseParams[i]
                                            });
                                        }
                                        cgsPanel.doLayout();
                                    }
                                    cgsPanel.getForm().submit({
                                        clientValidation: true,
                                        url: cgsUrl,
                                        success: function(form, action) {
                                            alert("Successful submitting " + cgsUrl);
                                        },
                                        failure: function(form, action) {
                                            alert("Failed processing CGS");
                                            switch (action.failureType) {
                                                case Ext.form.Action.CLIENT_INVALID:
                                                    alert("Form fields may not be submitted with invalid values");
                                                    break;
                                                case Ext.form.Action.CONNECT_FAILURE:
                                                    alert("Ajax communication failed");
                                                    break;
                                                case Ext.form.Action.SERVER_INVALID:
                                                    alert("Failure", action.result.msg);
                                                default:
                                                    alert("Upload failed");
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            }
        ];
        var bamLink = "";
        var baiLink = "";
        var alias = "";
        if (YCGSHash != null) {
            alias = YCGSHash.YCGSStrain.replace(/_/g, "");
            buttons = [
                {
                    id: 'updateYCGSButtonId',
                    name: 'updateYCGSButton',
                    text: 'Update',
                    listeners: {click:
                            function() {
                                updateYCGSStrain();
                            }
                    }
                }
            ];
            var link = "sequencing/igv/custom_config/" + YCGSHash.name + "_" + YCGSHash.YCGSSeqRun + "_" + alias + "/jnlp";
            bamLink = "/igv/" + YCGSHash.name + "_" + YCGSHash.YCGSSeqRun + "_" + YCGSHash.YCGSStrain + ".bam";
            bamLink = "<a href='" + bamLink + "' target='_blank'>bam" + "</a>";
            baiLink = "/igv/" + YCGSHash.name + "_" + YCGSHash.YCGSSeqRun + "_" + YCGSHash.YCGSStrain + ".bai";
            baiLink = "<a href='" + baiLink + "' target='_blank'>bai" + "</a>";
            mytbar = [
                {
                    id: 'coverageCGSId',
                    text: 'CGSSummary',
                    icon: "images/smart.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Displays coverage summary statistics',
                    listeners: {click:
                            function() {
                                renderSummaryPV(YCGSHash.name, YCGSHash.YCGSCoverage, YCGSHash.YCGSPercentage);
                            }
                    }
                },
                {
                    id: 'classificationCGSId',
                    text: 'FilterClassifications',
                    icon: "images/search-blue.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Displays classification information',
                    listeners: {click:
                            function() {
                                Ext.MessageBox.prompt('Search', 'Enter chromosome range(ie chrI:1000-10000) or gene or keyword:', function(btn, text) {
                                    if (btn == "ok" && text.length > 1 && text.indexOf("chr") == -1) {
                                        var geneUri = "/dudley-lims/sequencing/cgs/translategenename?genename=" + text;
                                        Ext.Ajax.request({
                                            url: geneUri,
                                            method: "GET",
                                            success: function(response) {
                                                var respObj = Ext.util.JSON.decode(response.responseText);
                                                loadClassificationTab(YCGSHash.name, respObj["systematicname"]);
                                            },
                                            failure: function(response) {
                                                alert("Failed on retrieving systematic gene name for:" + text + " Filtering on all");
                                                loadClassificationTab(YCGSHash.name, text);
                                            }
                                        });
                                    } else if (btn == "ok") {
                                        loadClassificationTab(YCGSHash.name, text);
                                    }
                                });
                            }
                    }
                },
                {
                    text: 'SNPClassifications@IGV',
                    icon: "images/igv.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Activates IGV with custom mutation tracks for this CGS',
                    listeners: {
                        render: function(c) {
                            Ext.QuickTips.register({
                                target: c,
                                title: '',
                                text: 'Button launches Integrated Genome Viewer for visualizing strain variations with reference'
                            });
                        },
                        click: function(c) {
                            Ext.MessageBox.prompt('Gene-Locus', 'Enter optional gene or locus(ie chrI:200-1000):', function(btn, text) {
                                if (text && text.length > 1) {
                                    var parsedLink = link.split(alias);
                                    link = parsedLink[0] + alias + "locuz:" + text + "/jnlp";
                                }
                                if (btn == "ok")
                                    window.open(link, '_blank');
                            });
                        }
                    }
                },
                    {
                    id: 'detailSpotlightYCRId',
                    disabled: false,
                    text: 'Spotlight',
                    icon: "images/add-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Add to spotlight',
                    listeners: {
                        click: function() {
                            var selectedArray = [YCGSHash.name, YCGSHash.name, YCGSHash.YCGSSeqRun + ":" + YCGSHash.YCGSStrain];
                            sptlght.utils.SpotlightUtils.setSelectedRecord(selectedArray);
                            sptlght.utils.SpotlightUtils.setSource("ycgs");
                            sptlght.utils.SpotlightUtils.handleAddToSpotlight();
                        }
                    }
                }
            ];
        } else {
            YCGSHash = new Object();
            var YCGSMaxInt = parseInt(YCGSMaxNum);
            YCGSMaxInt = YCGSMaxInt + 1;
            var YCGSCountInt = parseInt(YCGSCount);
            YCGSCountInt = YCGSCountInt + 1;
            YCGSCount = YCGSCountInt + "";
            YCGSHash.name = 'YCGS' + YCGSMaxInt;
            YCGSMaxNum = YCGSMaxInt + "";
            YCGSHash.YCGSComments = "";
        }

        if (selectedSeqRec["strain"] != null) {
            YCGSHash.YCGSSeqRun = selectedSeqRec["seqrun"];
            YCGSHash.project = selectedSeqRec["project"];
            YCGSHash.YCGSFlowcell = selectedSeqRec["flowcell"];
            YCGSHash.YCGSLane = selectedSeqRec["lane"];
            YCGSHash.YCGSStrain = selectedSeqRec["strain"];
        }


        YCGSForm = new Ext.form.FormPanel({
            id: 'YCGSForm',
            autoHeight: true,
            autoScroll: true,
            title: 'Complete Genome Sequence',
            border: true,
            buttonAlign: 'left',
            url: '/dudley-lims/sequencing/cgs/submit',
            method: 'POST',
            fileUpload : true,
            buttons: buttons,
            tbar: mytbar,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "YCGSKeyId",
                            fieldLabel: "Key",
                            name: "YCGSKey",
                            value: YCGSHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false
                        }),
                        getDudleyProjectCombo("YCGS", YCGSHash),
                        new Ext.form.TextField({
                            id: "YCGSSeqRun",
                            fieldLabel: "YSEQKey",
                            value: YCGSHash.YCGSSeqRun,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Enter YSEQ key associated with CGS'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "YCGSStrain",
                            fieldLabel: "StrainKey",
                            value: YCGSHash.YCGSStrain,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Enter Strain key associated with CGS'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "YCGSFlowcell",
                            fieldLabel: "Flowcell",
                            value: YCGSHash.YCGSFlowcell,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Enter flowcell associated with CGS'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "YCGSLane",
                            fieldLabel: "Lane",
                            value: YCGSHash.YCGSLane,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Enter lane associated with CGS'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextArea({
                            id: "YCGSMethods",
                            fieldLabel: "Method Description",
                            value: YCGSHash.YCGSMethods,
                            width: 500,
                            height: 100,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Captures bam/sam associated with strain/sequence lane'
                                    });
                                }
                            }
                        }),
                        {
                            xtype:'htmleditor',
                            id:'YCGSMutationFiles',
                            value: "",
                            fieldLabel: "CGS Files",
                            height:250,
                            anchor:'98%',
                            readOnly: true,
                            listeners: {
                                render: function(c) {
                                    Ext.Ajax.request({
                                        url: "/addama-rest/dudley-sample/path/datasource/YCGS/" + YCGSHash.name + "/dir",
                                        method: "GET",
                                        success: function(response) {
                                            var dirObj = Ext.util.JSON.decode(response.responseText);
                                            var files = dirObj.files;
                                            var links = "";
                                            if (files){
                                                files.sort(function(a, b) {
                                                    return a.name > b.name
                                                });
                                                for (var file in files) {
                                                    var mLink = "<a href='" + files[file].uri + "' target='_blank'>" + files[file].name + "</a><br>";
                                                    links = links + mLink;
                                                }
                                                links = bamLink + "/" + baiLink + "<br>" + links;
                                                //alert(links);
                                                }
                                            c.setValue(links);
                                        },
                                        failure: function() {
                                            eventManager.fireStatusMessageEvent({ text: "Failed Retriving mutations files for key:" + YCGSHash.name , level: "error" });
                                        }
                                    });
                                }
                            }
                        },

                        {
                            xtype:'htmleditor',
                            id:'YCGSComments',
                            value: YCGSHash.YCGSComments,
                            fieldLabel:'Comments',
                            height:100,
                            //labelSeparator: '',
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (YCGSHash.comments == undefined || YCGSHash.comments == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        }
                    ]
                })
            ]
        });
        callback();
    }

    function updateYCGSStrain() {
        var cgsJson = new Object();
        var cgsKey = Ext.getCmp("YCGSKeyId").getValue();
        cgsJson["YCGSKey"] = cgsKey;
        cgsJson["YCGSName"] = cgsKey;
        cgsJson["YCGSDudleyProject"] = Ext.getCmp("YCGSDudleyProject").getValue();
        cgsJson["YCGSSeqRun"] = Ext.getCmp("YCGSSeqRun").getValue();
        cgsJson["YCGSStrain"] = Ext.getCmp("YCGSStrain").getValue();
        cgsJson["YCGSFlowcell"] = Ext.getCmp("YCGSFlowcell").getValue();
        cgsJson["YCGSLane"] = Ext.getCmp("YCGSLane").getValue();
        //cgsJson["YCGSBuild"] = Ext.getCmp("YCGSBuild").getValue();
        cgsJson["YCGSComments"] = Ext.getCmp("YCGSComments").getRawValue();
        cgsJson["YCGSMethods"] = Ext.getCmp("YCGSMethods").getRawValue();

        //cgsJson["mutationFiles"] = Ext.getCmp("YCGSMutationFiles").getRawValue();
        //cgsJson["YCGSBam"] = Ext.getCmp("YCGSBam").getValue();

        postDudleyAnnotations("/addama-rest/dudley-sample/path/datasource/YCGS/" + cgsKey + "/annotations", cgsJson, function() {
            Ext.Msg.alert('Info', cgsKey + ' Updated Successfully');
            var searchResultsButton = Ext.getCmp("showYCGSSearchResultsId");
            searchResultsButton.disable();
        });
    }

    function renderYCGSDetails(selectedRow) {
        var searchResultsButton = Ext.getCmp("showYCGSSearchResultsId");
        if (searchResultsButton != null) {
            searchResultsButton.enable();
        }
        YCGSHash = new Object();
        if (selectedRow != null) {
            populateYCGSJson(YCGSHash, selectedRow);
        } else {
            populateSingleYCGSViaSearch(YCGSHash, myYCGSData[0]);
        }
        var resourceUri = "/addama-rest/dudley-sample/path/datasource/YCGS/" + YCGSHash.name;
        Ext.Ajax.request({
            url: resourceUri + "/mayUpdate",
            method: "GET",
            params: {
                "user_uri": LoggedInUser.userUri
            },
            success: function() {
                loadCreateYCGSStrain(YCGSHash, function() {
                    //var snpFileField = Ext.getCmp("cgsSNPFileId");
                    //snpFileField.setDisabled(true);
                    //var fastQFileField = Ext.getCmp("cgsFastQFileId");
                    //fastQFileField.setDisabled(true);
                    YCGSFormRender();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Read only access allowed", level: "info" });
                loadCreateYCGSStrain(YCGSHash, function() {
                    var updateYCGSButton = Ext.getCmp("updateYCGSButtonId");
                    if (updateYCGSButton != undefined) {
                        updateYCGSButton.hidden = true;
                    }

                    YCGSFormRender();
                });
            }
        });

    }

    // render the grid to the specified div in the page
    function renderYCGSSearchResult() {
        if (myYCGSData.length == 1) {
            renderYCGSDetails(null);
            return;
        }
        var searchResultsButton = Ext.getCmp("showYCGSSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        pagingBar =new Ext.PagingToolbar({
                pageSize: 10,
                store: YCGSStore,
                displayInfo: true,
                displayMsg: 'Displaying strains {0} - {1} of {2}',
                emptyMsg: "No strains to display"
            });
        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "YCGSSearchResultsId",
            store: YCGSStore,
            columns: getYCGSSearchColumnHeaders(),
            stripeRows: true,
            autoHeight: true,
            autoScroll: true,
            width: 800,
            title: 'YCGS',
            renderTo: "yseq-search-results",
            tbar: [
                            {
                                id: 'crossing2CSVId',
                                text: 'Export2CSV',
                                icon: "images/check-green.png",
                                cls:'x-btn-text-icon',
                                tooltip: 'Export search results to csv',
                                listeners: {click:
                                        function() {
                                            Dudley.lims.YSEQCGS.toCSV(myYCGSData, "YCGSSearchedResults.csv");
                                        }
                                }
                            }
                        ],
            bbar: pagingBar
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            renderYCGSDetails(g);
        });
     searchResultsGrid.on("rowcontextmenu", onMessageContextMenu);
    }

    function onMessageContextMenu(grid, rowIndex, e) {
        var activePage = Math.ceil((pagingBar.cursor + pagingBar.pageSize) / pagingBar.pageSize);
        var realIndex = (activePage - 1) * pagingBar.pageSize + rowIndex;
        sptlght.utils.SpotlightUtils.setSelectedRecord(YCGSStore.allData.items[realIndex].json);
        sptlght.utils.SpotlightUtils.setSource("ycgs");
        e.preventDefault();
        e.stopEvent();
        var coords = e.getXY();
        spotlightMenu.showAt([coords[0], coords[1]]);
    }
    function YCGSFormRender() {
        var omicsPanel = Dudley.lims.sequencingmgr.getOmicPanel();
        omicsPanel.activate(YCGSPanel);
        Dudley.lims.sequencingmgr.clearPane();
        YCGSForm.render("wo-form");
    }

    // public
    return {
        initCGS: function(failedCB) {
            initYCGSStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init YCGS Store", level: "info" });
            });
        },

        getCGSPanel: function(doRender) {
            loadYCGSPanel(doRender);
            return YCGSPanel;
        },

        getCGSPanelInst: function() {
            return YCGSPanel;
        },

        setCGSLoaded: function(boo) {
            YCGSLoaded = boo;
        },
        setCGSSearchParams: function(myParam, myOption) {
            searchInput = myParam;
            searchOption = myOption;
        },

        getCGSLoaded: function() {
            return YCGSLoaded;
        },
        loadCGSSearch: function() {
            goSearch(0, searchInput, searchOption);
        },

        getCGSStore: function() {
            return YCGSStore;
        },

        classifyCGS: function() {
            alert("display form for classification entry");
        },

        loadNewYCGS: function(seqRec) {
            Ext.getDom("wo-form").innerHTML = "";
            if (LoggedInUser.userUri == "/addama-users/users/public@systemsbiology.org") {
                Ext.Msg.alert("warning", "You not have permission to create new YCGSs");
            } else {
                Ext.Ajax.request({
                    url: "/addama-rest/dudley-sample/path/datasource/YCGS/annotations",
                    method: "GET",
                    success: function(response) {
                        var yoAnnoObj = Ext.util.JSON.decode(response.responseText);
                        YCGSCount = yoAnnoObj.YCGSCount;
                        YCGSMaxNum = yoAnnoObj.YCGSMaxNum;
                        YCGSHash = null;
                        selectedSeqRec = seqRec;
                        var searchResultsButton = Ext.getCmp("showYCGSSearchResultsId");
                        searchResultsButton.enable();
                        loadCreateYCGSStrain(YCGSHash, function() {
                            Dudley.lims.sequencingmgr.clearPane();
                            YCGSForm.render("wo-form");
                        });
                    },
                    failure: function() {
                        eventManager.fireStatusMessageEvent({ text: "Failed Getting Annotations for YCGS Datasource", level: "error" });
                    }
                });
            }
        },
        loadSearchResult: function() {
            Ext.getDom("yseq-search-results").innerHTML = "";
            renderYCGSSearchResult();
        },

         toCSV: function(myData, csvname) {
            var csvText = "ycgsKey,ycgsProject,ycgsSeqRun,ycgsStrain,ycgsFlowcell,ycgsLane,ycgsHasBam,ycgsBam,ycgsComments,ycgsBuild,ycgsCoverage,ycgsPercentage,ycgsMethod,ycgsFiles" + breakDelimiter;
            myData.sort(function(a, b) {
                return a[0] - b[0];
            });
            for (var c = 0; c < myData.length; c++) {
                var pline = "";
                var cArray = myData[c];
                for (var ci = 0; ci < cArray.length; ci++) {
                    if (cArray[ci] == undefined || cArray[ci] == null) {
                        cArray[ci] = "";
                    }
                    cArray[ci] = cArray[ci] + "";
                    cArray[ci] = cArray[ci].replace(/'/g, "");
                    cArray[ci] = '"' + cArray[ci] + '"';
                    cArray[ci] = cArray[ci].replace(/YPG /g, "YPG");
                    cArray[ci] = cArray[ci].replace(/YO /, "YO");
                    cArray[ci] = cArray[ci].replace(/YAD /, "YAD");
                }
                csvText = csvText + "" + cArray[1] + "," + cArray[3] + "," + cArray[4] + "," + cArray[5] + "," + cArray[6] + "," + cArray[7]
                        + "," + cArray[8] + "," + cArray[9] + "," + cArray[10] + "," + cArray[11]
                        + "," + cArray[12] + "," + cArray[13] + "," + cArray[14] + breakDelimiter;
                pline = pline + cArray[ci] + ",";

            }
            csvText = csvText + pline.substr(0, pline.length - 1) + breakDelimiter;
            export2Csv(csvname, csvText, "YCGS2Csv");
        },
        setArrayData: function(data) {
                    myYCGSData = data;
         }
    };
}
        ();
